package de.breitbeil.jbooking.ui.dialog;

import java.util.Calendar;

import org.springframework.richclient.dialog.FormBackedDialogPage;
import org.springframework.richclient.dialog.TitledPageApplicationDialog;
import org.springframework.richclient.form.Form;
import org.springframework.richclient.settings.SettingsException;
import org.springframework.richclient.settings.SettingsManager;

import de.breitbeil.jbooking.task.CalendarExportTask;
import de.breitbeil.jbooking.ui.form.SaveCalendarForm;
import de.breitbeil.jbooking.ui.form.SaveCalendarFormObject;

public class SaveCalendarDialog extends TitledPageApplicationDialog {

    public static final String ID = "saveCalendarDialog";
    
    private Form form;
    private SaveCalendarFormObject formObject;
    
    public SaveCalendarDialog(SettingsManager settingsManager) throws SettingsException {
        formObject = new SaveCalendarFormObject();
        formObject.init(settingsManager.getUserSettings());
        
        form = new SaveCalendarForm(formObject);
        
        setDialogPage(new FormBackedDialogPage(form));
    }

    protected void onInitialized() {
        super.onInitialized();

        setTitle(getMessage(ID + ".title"));
        setTitlePaneTitle(getMessage(ID + ".title"));
        setDescription(getMessage(ID + ".description"));

        setResizable(false);
    }
    
    @Override
    protected boolean onFinish() {
        form.commit();
        SaveCalendarFormObject formObject = (SaveCalendarFormObject) form.getFormObject();
        String filename = formObject.getFilename();
        String suffix = formObject.getSuffix();
        
        if(!filename.toLowerCase().endsWith(suffix.toLowerCase())) {
            filename = filename + "." + formObject.getSuffix();
        }
        
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(formObject.getFirstDisplayedDay());
        
        // Save calendar to file
        CalendarExportTask task = new CalendarExportTask(calendar, filename);
        task.execute();
        
        return true;
    }
    
}
